package com.api.syh56.shengyunhui.controller.admin;

import cn.hutool.core.date.DateTime;
import com.api.syh56.shengyunhui.common.*;
import com.api.syh56.shengyunhui.entity.User;
import com.api.syh56.shengyunhui.entity.WithDraw;
import com.api.syh56.shengyunhui.entity.vo.AdminWithDrawVO;
import com.api.syh56.shengyunhui.exception.BaseException;
import com.api.syh56.shengyunhui.service.SystemMessageService;
import com.api.syh56.shengyunhui.service.UserService;
import com.api.syh56.shengyunhui.service.WithDrawService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("admin/withdraw")
public class AdminWithDrawController {
    @Autowired
    private WithDrawService withDrawService;

    @Autowired
    private UserService userService;

    @Autowired
    private SystemMessageService systemMessageService;

    /**
     * 管理员提现申请列表
     */
    @GetMapping("list")
//    public CommonResult<CommonPage<WithDraw>> adminWithdrawList(@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
    public CommonResult<CommonPage<AdminWithDrawVO>> adminWithdrawList(@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                @RequestParam(value = "state", defaultValue = "") Short state,
                                                                @RequestParam(value = "beginTime", defaultValue = "")  @DateTimeFormat(pattern = "yyyy-MM-dd") String beginTime,
                                                                @RequestParam(value = "endTime", defaultValue = "")  @DateTimeFormat(pattern = "yyyy-MM-dd") String endTime,
                                                                @RequestParam(value = "companyName", defaultValue = "") String companyName,
                                                                @RequestParam(value = "bankAccount", defaultValue = "") String bankAccount) {

        Page<WithDraw> page = new Page<>(pageNum,pageSize);
        //查询提现申请中的金额
        QueryWrapper<WithDraw> withDrawQueryWrapper = new QueryWrapper<>();
        if (state != null) {
            withDrawQueryWrapper.lambda().eq(WithDraw::getState, state);
        }
        //如果时间不为空字符串，则查询时间
        if (!"".equals(beginTime)) {
            LocalDateTime beginLocalDateTime = LocalDateTime.parse(beginTime,Constants.DateTimeFormatterType.ISO8601_yMd);
            withDrawQueryWrapper.lambda().ge(WithDraw::getCreationTime, beginLocalDateTime);
        }
        if (!"".equals(endTime)) {
            LocalDateTime endLocalDateTime = LocalDateTime.parse(endTime,Constants.DateTimeFormatterType.ISO8601_yMd);
            withDrawQueryWrapper.lambda().le(WithDraw::getCreationTime, endLocalDateTime);
        }
        if (!"".equals(companyName)) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda().eq(User::getCompany, companyName);
            User userDB = userService.getOne(userQueryWrapper);
            Long uid = userDB.getId();
            withDrawQueryWrapper.lambda().eq(WithDraw::getUid, uid);
        }
        if (!"".equals(bankAccount)) {
            withDrawQueryWrapper.lambda().eq(WithDraw::getBankAccount, bankAccount);
        }

        withDrawQueryWrapper.lambda().orderByDesc(WithDraw::getCreationTime);

        Page<WithDraw> withDrawPage = withDrawService.page(page, withDrawQueryWrapper);

        List<WithDraw> records = withDrawPage.getRecords();
        ArrayList<AdminWithDrawVO> adminWithDrawVOS = new ArrayList<>();
        for (WithDraw withDraw : records){
            AdminWithDrawVO adminWithDrawVO = new AdminWithDrawVO();
            adminWithDrawVO.setWithDraw(withDraw);
            Long uid = withDraw.getUid();
            User user = userService.getById(uid);
            String company = user.getCompany();
            String telephone = user.getTelephone();
            adminWithDrawVO.setCompany(company);
            adminWithDrawVO.setTelephone(telephone);
            adminWithDrawVOS.add(adminWithDrawVO);
        }
        Page<AdminWithDrawVO> adminWithDrawVOPage = new Page<>();
        adminWithDrawVOPage.setRecords(adminWithDrawVOS);
        adminWithDrawVOPage.setCurrent(withDrawPage.getCurrent());
        adminWithDrawVOPage.setSize(withDrawPage.getSize());
        adminWithDrawVOPage.setTotal(withDrawPage.getTotal());
        adminWithDrawVOPage.setPages(withDrawPage.getPages());
//        return CommonResult.success(CommonPage.restPage(withDrawPage));
        return CommonResult.success(CommonPage.restPage(adminWithDrawVOPage));
    }

    /**
     * 管理员审核提现申请
     */
    @PostMapping("audit")
    @Transactional
    public CommonResult<WithDraw> adminWithDrawAudit(@RequestBody WithDraw withDraw) {
        Long id = withDraw.getId();
        Short state = withDraw.getState();
        String imgPath = withDraw.getImgPath();
        String description = withDraw.getDescription();



        WithDraw withDrawDB = withDrawService.getById(id);
        LocalDateTime localDateTime = withDrawDB.getCreationTime();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 使用DateTimeFormatter将LocalDateTime格式化为字符串
        String formattedDateTime = localDateTime.format(formatter);


        Short currentState = withDrawDB.getState();
        if (currentState == Constants.WithdrawalStatus.SUCCESS || currentState == Constants.WithdrawalStatus.FAILED) {
            return CommonResult.failed("该提现申请已被审核完成，请勿重复审核");
        }

        if (state == Constants.WithdrawalStatus.SUCCESS || state == Constants.WithdrawalStatus.FAILED ) {
            withDrawDB.setState(state);
            withDrawDB.setImgPath(imgPath);
            withDrawDB.setDescription(description);
            withDrawDB.setAdminTime(LocalDateTime.now());
            withDrawService.updateById(withDrawDB);

            //提现成功，扣除用户余额
            Long uid = withDrawDB.getUid();

            if( withDrawDB.getState() == Constants.WithdrawalStatus.SUCCESS) {
                //提现成功，扣除用户余额
                userService.reduceBalance(uid, withDrawDB.getAmount());
                systemMessageService.sendWithDrawSuccess(uid,formattedDateTime);
            }else {
                if (description.isEmpty()) {
                    throw new BaseException("请输入失败原因");
                }
                systemMessageService.sendWithDrawFailed(uid, formattedDateTime,description);
                //提现失败，不扣除用户余额
            }

            return CommonResult.success(withDrawDB);
        }else {
            return CommonResult.failed("提现申请状态只可为成功或失败");
        }

    }
}
